package com.tyqx.hashchainbiz.service.impl;

// import com.alibaba.fastjson.JSON;
import com.tyqx.hashchainbean.module.HashIndex;
import com.tyqx.hashchainbean.module.UseProduct;
import com.tyqx.hashchainbiz.service.UseProductService;
import com.tyqx.hashchaindao.mapper.HashIndexMapper;
import com.tyqx.hashchaindao.mapper.UseProductMapper;
import com.tyqx.hashchainutil.common.HashValueUtil;
import com.tyqx.hashchainutil.common.mongodb.ImagePathHashValueUtil;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service("useProductService")
public class UseProductServiceImpl implements UseProductService {


    @Resource
    private HashIndexMapper hashIndexMapper;

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private UseProductMapper useProductMapper;

    @Async
    public Integer useProduct(UseProduct useProduct) throws Exception{
        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime=sdf.parse(sdf.format(currentDate));
        useProduct.setCreateTime(createTime);
        useProduct.setUpdateTime(createTime);
        String useProductStr= useProduct.toString();


        String attachmentStr=useProduct.getAttachment();
        if (!"".equals(attachmentStr) && attachmentStr != null) {
            String collectionName = "useProduct";
            String imageHashValue = ImagePathHashValueUtil.insertAttachment(attachmentStr, mongoTemplate, collectionName);
            useProduct.setAttachment(imageHashValue);
        }
        HashIndex hashIndex= HashValueUtil.getHashValue(useProductStr);
        Integer flag=hashIndexMapper.insert(hashIndex);

        useProduct.setHashValue(hashIndex.getHashValue());
        return useProductMapper.addUseProduct(useProduct);
    }

    @Override
    public List<UseProduct> getUseProductById(String donateId, String userName) {
        return useProductMapper.getUseProductById(donateId);
    }

    @Override
    public List<UseProduct> getUseProductByTime(Date startTime, Date endTime, String userName) {
        return useProductMapper.getUseProductByTime(startTime, endTime, userName);
    }
}
